import { login, logout, info } from '@/system/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'

const user = {
	state: {
		token: getToken(),
		info: null,
		loginstatus: sessionStorage.getItem('loginstatus') || false,
	},

	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token
		},
		SET_USERINFO: (state, info) => {
			state.info = info
		},
		SET_LOGINSTATE: (state, loginstatus) => {
			state.loginstatus = loginstatus
			sessionStorage.setItem('loginstatus', loginstatus)
		},
	},

	actions: {
		// 登录
		Login({ commit }, userInfo) {
			return new Promise((resolve, reject) => {
				login(userInfo)
					.then(res => {
						if (res.success) {
							setToken(res.info)
							commit('SET_TOKEN', res.info)
							commit('SET_LOGINSTATE', true)
							resolve(res)
						} else {
							resolve(res)
						}
					})
					.catch(error => {
						reject(error)
					})
			})
		},

		// 获取用户信息
		GetInfo({ commit, state }) {
			return new Promise((resolve, reject) => {
				info()
					.then(res => {
						commit('SET_USERINFO', res.info)
						resolve(res)
					})
					.catch(error => {
						reject(error)
					})
			})
		},

		// 退出系统
		LogOut({ commit, state }) {
			return new Promise((resolve, reject) => {
				logout(state.token)
					.then(() => {
						commit('SET_TOKEN', '')
						commit('SET_USERINFO', null)
						commit('SET_LOGINSTATE', false)
						commit('clearAllTags')
						removeToken()
						//        location.reload()
						resolve()
					})
					.catch(error => {
						reject(error)
					})
			})
		},

		// 前端 登出
		FedLogOut({ commit }) {
			return new Promise(resolve => {
				commit('SET_TOKEN', '')
				commit('SET_USERINFO', null)
				commit('SET_LOGINSTATE', false)
				commit('permission/SET_ROUTES', [])
				removeToken()
				resolve()
			})
		},
	},
}

export default user
